<template>
   <el-row :gutter="20" :style="{'margin-top':'10%'}">
     <el-col   :xs="{span:20,push:2}" :sm="{span:12,push:6}" :md="{span:10,push:7}" :lg="{span:8,push:8}" >
       <el-card shadow="always" :body-style="{ padding: '20px' }">
         <el-form :model="user" ref="userForm" :rules="rules" label-width="80px" :inline="false" size="normal">
           <el-form-item label="邮箱：" prop="email">
             <el-input type="text" v-model="user.email" ></el-input>
           </el-form-item>
           <el-form-item label="用户名：" prop="userName">
             <el-input type="text" v-model="user.userName" ></el-input>
           </el-form-item>
          <el-form-item label="密码：" prop="newPassword">
             <el-input type="text" v-model="user.newPassword"  show-password></el-input>
           </el-form-item>
          <el-form-item label="再次输入密码：" prop="oldPassword">
             <el-input type="text" v-model="user.oldPassword"  show-password></el-input>
           </el-form-item>
          <el-form-item label="性别：" >
             <el-radio v-model="user.userSex" label="M">男</el-radio>
             <el-radio v-model="user.userSex" label="F">女</el-radio>
          </el-form-item>
          <el-form-item label="验证码：" prop="code">
             <el-input type="text" v-model="user.code" ></el-input>
          </el-form-item>
          <el-row >
            <el-col  :span="24"  :style="{'text-align':'center'}" >
              <el-button type="primary" @click="onSubmit">提交</el-button>
              <el-button type="primary" @click="onReset()">重置</el-button>
              <el-button type="primary" @click="getCode()" :disabled="isCode">{{butCode}}</el-button>
            </el-col>
          </el-row>
         </el-form>
       </el-card>
     </el-col>
   </el-row>
</template>

<script lang="ts">
  import { Component, Vue, Ref } from 'vue-property-decorator';
  import {ElForm,ValidateCallback,ValidateFieldCallback} from 'element-ui/types/form';
  import UserRegist from '@/domain/UserRegist';
  import http from '@/utils/request';
  import Rules,{Validator,Rule} from '@/domain/Rules';
  import {AxiosResponse} from "axios";
  import router from '@/router';
  import VerificationType from "@/domain/VerificationType"
  import Verification from '@/domain/Verification';

  //字符串中含有空字符
  let trimValidator:Validator=(rules:any,value:string,calllback:Function):void=>{
             if (value.length>value.trim().length) {
               calllback(new Error('不能含有空格'));
               return;
             }
             calllback();
  };

//  密码校验规则
  const  pwdValidatorArr:Array<Rule>=[
          {
          "trigger":"change",
          "required":true,
          "message":"请输入密码"
          },
          {
          "trigger":"change",
          "min":6,
          "max":20,
          "message":"密码字符在6-20"
          },
          {
          "trigger":"change",
          "validator":trimValidator,
          "message":"密码不能存在空字符"
          },
        ];

// 邮箱校验规则
const emailValidatorArr:Array<Rule>=[
          {
          "trigger":"change",
          "required":true,
          "message":"请输入邮箱"
          },
          {
          "trigger":"change",
          "min":1,
          "max":20,
          "message":"邮箱字符限制在20个字符内"
          },
          {
          "type":"email",
          "trigger":"change",
          "message":"不符合邮箱格式"
          },
        ];

// 用户名校验规则
const userNameValidatorArr:Array<Rule>=[
          {
          "trigger":"change",
          "required":true,
          "message":"请输入用户名"
          },
          {
          "trigger":"change",
          "min":1,
          "max":20,
          "message":"用户名字符限制在20个字符内"
          }
        ];
// 用户名校验规则
const codeValidatorArr:Array<Rule>=[
          {
          "trigger":"change",
          "required":true,
          "message":"请输入验证码"
          },
          {
          "trigger":"change",
          "min":6,
          "max":6,
          "message":"验证码必须是6个字符"
          }
        ];



   @Component
   class Registration extends Vue {
      user:UserRegist={email:"",newPassword:"",oldPassword:"",userName:"",userSex:undefined,code:undefined};
      butCode:string ='获取验证码';
      isCode:boolean = false;
      readonly rules:Rules={
        "email":emailValidatorArr,
        "oldPassword":pwdValidatorArr,
        "newPassword":pwdValidatorArr,
        "userName":userNameValidatorArr,
        "code":codeValidatorArr,
      };


      @Ref('userForm')  readonly userform!:ElForm;

      onSubmit():void{
        //参数校验
        let  callback:ValidateCallback= (isValid: boolean, invalidFields: object): void=>{
          if(isValid){
            http({
              url:'/user/registration',
              method:'POST',
              data:this.user
            }).then((resp):void=>{
                router.push('/login').catch((rea:any):any=>{});  
            })
            return;
          }
          console.error('请求参数校验失败')
        };
        this.userform.validate(callback)
      }

      onReset():void{
        this.userform.resetFields();
      }

      getCode():void{
        let  callback:ValidateFieldCallback= (errorMessage: string): void=>{
          if(!errorMessage){
            let us:Verification = {email:this.user.email,type:VerificationType.REGIST} ;
            http({
              url:'/user/verificationCode',
              method:'get',
              params: us
            }).then((resp:AxiosResponse):void=>{
              this.isCode = true;
              this.setTime(120);
            })            
            return;
          }
          console.error('请求参数校验失败')
        };
        this.userform.validateField(['email'],callback)
      }

      setTime(num:number):void{
          if(num==0){
            this.isCode = false;
            this.butCode = '获取验证码';
            return;
          }
          setTimeout(() => {
            num--;
            this.butCode='获取验证码('+num+')'
            this.setTime(num);
          }, 1000);
      }
  }
  export default Registration;
</script>
